package com.example.jd.finance.jpush;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.Notification;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PushClient {
	protected static final Logger LOG = LoggerFactory.getLogger(PushClient.class);

	protected static final String APP_KEY = "dcbfb95294902de54772d988";
	protected static final String MASTER_SECRET = "def2b99aa9c02c90d4712234";

	private static long sendTotalTime = 0;

	public static int AppSendPush(String alias, String alert) {
		LOG.info("推送开始，内容为：{}",alert);
		ClientConfig clientConfig = ClientConfig.getInstance();
		final JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, clientConfig);
		PushPayload payload = buildPushObject_alias_followUser(alias, alert);
		try {
			PushResult result = jpushClient.sendPush(payload);
			LOG.info("得到了结果 - " + result);
			return result.getResponseCode();
		} catch (APIConnectionException e) {
			LOG.error("连接错误,应该稍后重试!", e);
			LOG.error("Sendno: " + payload.getSendno());
			return 10020;
		} catch (APIRequestException e) {
			LOG.error("从JPush服务器错误响应,应该检查并修复它! ", e);
			LOG.info("HTTP Status: " + e.getStatus());
			LOG.info("Error Code: " + e.getErrorCode());
			LOG.info("Error Message: " + e.getErrorMessage());
			LOG.info("Msg ID: " + e.getMsgId());
			LOG.error("Sendno: " + payload.getSendno());
			return 10010;
		}
	}

	public static PushPayload buildPushObject_alias_followUser(String alias, String alert) {
		return PushPayload.newBuilder().setPlatform(Platform.android())
				.setAudience(Audience.alias(alias))
				.setMessage(Message.content(alert))
				.setOptions(Options.newBuilder()
						.setApnsProduction(false)
						.setTimeToLive(sendTotalTime)
						.build())
				.build();
	}

}
